package com.cgx.tablet.beeper.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.cgx.tablet.beeper.R;
import com.cgx.tablet.beeper.activity.LoginActivity;
import com.cgx.tablet.beeper.api.ApiCallback;
import com.cgx.tablet.beeper.bean.response.BaseResponse;
import com.cgx.tablet.beeper.bean.response.ErrorResponse;
import com.cgx.tablet.beeper.utils.JSONHelper;
import com.cgx.tablet.beeper.utils.ToastUtil;

import java.net.UnknownHostException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Retrofit调用
 * Created by cgx on 2018/9/8.
 */

public class BasePresenter {

    private Object view;
    private Dialog loadingDialog;

    public BasePresenter(Object view) {
        this.view = view;
    }

    protected <T> void callApi(Call<T> call, ApiCallback<T> callback) {
        callApi(call, callback, true);
    }

    protected <T> void callApi(Call<T> call, ApiCallback<T> callback, boolean needShowDialog) {
        callApi(call, callback, needShowDialog, true);
    }

    /**
     * 自定义的网络请求方法，为了取消dialog的时候同时取消网络请求
     *
     * @param call           retrofit的call
     * @param callback       自定义的callback
     * @param needShowDialog 是否现实加载对话框
     * @param cancelable     加载对话框是否可以取消
     * @param <T>            泛型
     */
    protected <T> void callApi(final Call<T> call, final ApiCallback<T> callback, boolean needShowDialog, boolean cancelable) {
        if (needShowDialog && view instanceof Context) {
            loadingDialog = new Dialog((Context) view, R.style.Translucent_NoTitle);
            loadingDialog.setContentView(R.layout.dialog_loading);
            loadingDialog.setCancelable(cancelable);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    call.cancel();
                }
            });
            loadingDialog.show();
        } else if (needShowDialog && view instanceof Fragment) {
            loadingDialog = new Dialog(((Fragment) view).getContext(), R.style.Translucent_NoTitle);
            loadingDialog.setContentView(R.layout.dialog_loading);
            loadingDialog.setCancelable(cancelable);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    call.cancel();
                }
            });
            loadingDialog.show();
        }

        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                hideLoadingDialog();
                try {
                    BaseResponse baseResponse = (BaseResponse) response.body();
                    ResponseBody errorBody = response.errorBody();
                    if (baseResponse != null) {
                        if (baseResponse.getState().equals("ok"))
                            callback.onSuccess(response.body());
                        else
                            callback.onFail(baseResponse.getCode(), baseResponse.getMessage());

                    } else if (errorBody != null) {
                        ErrorResponse errorResponse = JSONHelper.parse2Bean(errorBody.string(), ErrorResponse.class);
                        if (errorResponse.getCode().contains("sesstion")) {
                            if (view instanceof Context) {
                                ToastUtil.showLong((Context) view, errorResponse.getMessage());
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        Intent intent = new Intent();
                                        intent.setClass((Context) view, LoginActivity.class);
                                        ((Context) view).startActivity(intent);
                                    }
                                }, 3000);
                            } else if (view instanceof Fragment) {
                                ToastUtil.showLong(((Fragment) view).getContext(), errorResponse.getMessage());
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        Intent intent = new Intent();
                                        intent.setClass(((Fragment) view).getContext(), LoginActivity.class);
                                        ((Fragment) view).getContext().startActivity(intent);
                                    }
                                }, 3000);
                            }
                        }
                    }
                } catch (Exception e) {
                    callback.onFail("-999", "程序内部出现错误");
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                hideLoadingDialog();
                if (t instanceof UnknownHostException)
                    callback.onFail("-999", "网络异常，请检查网络");
                else {
                    if (!(TextUtils.equals(t.getMessage(), "Socket closed") || TextUtils.equals(t.getMessage(), "Canceled")))
                        callback.onFail("-999", "程序内部出现错误");
                }
            }
        });
    }

    /**
     * 隐藏加载对话框
     **/
    private void hideLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            if (view instanceof Context) {
                if (!((Activity) view).isFinishing()) {
                    loadingDialog.dismiss();
                }
            } else if (view instanceof Fragment) {
                if (!(((Fragment) view).getActivity()).isFinishing()) {
                    loadingDialog.dismiss();
                }
            }
            loadingDialog = null;
        }
    }
//
//    private void dumpExceptionToSDCard(Throwable ex) throws IOException {
//        // 以时间格式命名
//        SimpleDateFormat t = new SimpleDateFormat("yyyyMMddssSSS",
//                Locale.getDefault());
//        String pathname = filePath + (t.format(new Date())) + ".txt";
//
//        File file = new File(pathname);
//
//        try {
//            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
//            // 导出发生异常的时间
//            long current = System.currentTimeMillis();
//            String time = new SimpleDateFormat("yyyyMMdd HH:mm:ss",
//                    Locale.getDefault()).format(new Date(current));
//            pw.println(time);
//
//            // 导出手机信息
//            dumpPhoneInfo(pw);
//
//            pw.println();
//            // 导出异常的调用栈信息
//            ex.printStackTrace(pw);
//
//            pw.close();
//        } catch (Exception e) {
//            Log.e(TAG, "dump crash info failed");
//            Log.e(TAG, e.toString());
//        }
//    }
//
//    private void dumpPhoneInfo(PrintWriter pw) throws NameNotFoundException {
//        // 应用的版本名称和版本号
//        pw.print("App版本: ");
//        pw.print(appVersionName);
//        pw.print('_');
//        pw.println(appVersionCode);
//
//        // android版本号
//        pw.print("android版本: ");
//        pw.print(Build.VERSION.RELEASE);
//        pw.print("_");
//        pw.println(Build.VERSION.SDK_INT);
//
//        // 手机制造商
//        pw.print("手机制造商: ");
//        pw.println(Build.MANUFACTURER);
//
//        // 手机型号
//        pw.print("手机型号: ");
//        pw.println(Build.MODEL);
//
//        // cpu架构
//        pw.print("cpu架构: ");
//        pw.println(Build.CPU_ABI);
//    }

}
